//
//  HYDatePicker.m
//  HYDatePicker
//
//  Created by crte on 13-11-15.
//  Copyright (c) 2013年 crte. All rights reserved.
//

#import "HYDatePicker.h"

#define YEAR_CIRCULATE_TIMES 50
#define YEAR_COUNT 201

#define MONTH_CIRCULATE_TIMES 1000
#define MONTH_COUNT 12

#define DAY_CIRCULATE_TIMES 400

#define HOUR_CIRCULATE_TIMES 500
#define HOUR_COUNT 24

#define MINUTE_CIRCULATE_TIMES 200
#define MINUTE_COUNT 60

@interface HYDatePicker () <UIPickerViewDataSource, UIPickerViewDelegate>
{
    NSInteger yearRow;
    NSInteger mouthRow;
    NSInteger dayRow;
}

@property (nonatomic, weak) UIView *referView;

@property (nonatomic, strong) NSDate *defaultDate;

@property (nonatomic, assign) HYDatePickerType type;

@property (nonatomic, strong) HYDatePickerHandler handler;

//@property (nonatomic, strong) UIPickerView *pickerView;

// 完成并取消显示
@property (nonatomic, strong) UIButton *hideButton;

@property (nonatomic, strong) UIButton *cancelButton;

@property (nonatomic, assign) BOOL finished;

@end

@implementation HYDatePicker

- (id)initWithDate:(NSDate *)defaultDate type:(HYDatePickerType)type showInView:(UIView *)referView handler:(HYDatePickerHandler)handler
{
    self = [super initWithFrame:referView.bounds];
    if (self) {
        
        self.defaultDate = defaultDate;
        self.type = type;
        self.referView = referView;
        self.handler = handler;
        
        [self setup];
        
    }
    return self;
    
}



- (void)setup{
    // 背景
    self.backgroundColor = [UIColor whiteColor];
    // 创建全屏的透明隐藏按钮
    self.hideButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.hideButton.frame = CGRectMake(self.frame.size.width - 60, 10, 50, 30);
    [self.hideButton setTitle:@"确定" forState:UIControlStateNormal];
    [self.hideButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.hideButton addTarget:self action:@selector(hide) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:self.hideButton];
    
    
    self.cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.cancelButton.frame = CGRectMake(10, 10, 50, 30);
    [self.cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    [self.cancelButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.cancelButton addTarget:self action:@selector(cancel) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:self.cancelButton];
    
    
    
    //创建pickerView
    self.pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 300, self.frame.size.width, self.frame.size.height - 300)];
    self.pickerView.delegate = self;
    self.pickerView.dataSource = self;
    self.pickerView.showsSelectionIndicator = YES;
    [self addSubview:self.pickerView];
    
    //初始化年月日
    NSDate *nowDate = nil;
    if (self.defaultDate) {
        nowDate = self.defaultDate;
        
    } else {
        nowDate = [NSDate date];
        
    }
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd-HH-mm"];
    NSString *dateStr = [formatter stringFromDate:nowDate];
    NSArray *dateArray = [dateStr componentsSeparatedByString:@"-"];
    _year = [dateArray[0] intValue] - 24;
    _month = [dateArray[1] intValue];
    _day = [dateArray[2] intValue];
    _hour = [dateArray[3] intValue];
    _minute = [dateArray[4] intValue];
    
    //指向现在的时间
    [self.pickerView selectRow:[self calculateMiddleIndexWithFirstIndex:1990 - 1900  circulateTimes:YEAR_CIRCULATE_TIMES elementCount:YEAR_COUNT] inComponent:0 animated:NO];
    _year = 1990;
    [self.pickerView selectRow:[self calculateMiddleIndexWithFirstIndex:self.month - 1 circulateTimes:MONTH_CIRCULATE_TIMES elementCount:MONTH_COUNT] inComponent:1 animated:NO];
    
    [self.pickerView selectRow:[self calculateMiddleIndexWithFirstIndex:self.day - 1 circulateTimes:DAY_CIRCULATE_TIMES elementCount:[self calculateForDays]] inComponent:2 animated:NO];
    
    if (self.type == HYDatePickerTypeFull) {
        [self.pickerView selectRow:[self calculateMiddleIndexWithFirstIndex:self.hour circulateTimes:HOUR_CIRCULATE_TIMES elementCount:HOUR_COUNT] inComponent:3 animated:NO];
        [self.pickerView selectRow:[self calculateMiddleIndexWithFirstIndex:self.minute circulateTimes:MINUTE_CIRCULATE_TIMES elementCount:MINUTE_COUNT] inComponent:4 animated:NO];
        
    }
    
    
    
}

- (NSInteger)calculateMiddleIndexWithFirstIndex:(NSInteger)firstIndex circulateTimes:(NSInteger)times elementCount:(NSInteger)count
{
    if (times % 2 != 0) {
        times--;
        
    }
    
    NSInteger index = firstIndex + times / 2 * count;
    
    return index;
    
}

//计算选中的月份有多少天
- (NSInteger)calculateForDays
{
    NSCalendar *calendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM"];
    NSDate *date = [formatter dateFromString:[NSString stringWithFormat:@"%d-%d", self.year, self.month]];
    NSRange dayRange = [calendar rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:date];
    return dayRange.length;
    
}

- (void)show
{
    if (self.isShowing) {
        return;
        
    }
    
    [self.referView addSubview:self];
    self.alpha = 0;
    
    __block CGRect pickerRect = self.pickerView.frame;
    pickerRect.origin.y = self.bounds.size.height;
    self.pickerView.frame = pickerRect;
    
    [UIView animateWithDuration:0.25f animations:^{
        self.alpha = 1;
        
        pickerRect.origin.y -= self.pickerView.bounds.size.height;
        self.pickerView.frame = pickerRect;
        
    } completion:^(BOOL finished) {
        _show = YES;
        
    }];
    
}

- (void)hide
{
    if (!self.isShowing) {
        return;
        
    }
    
    [UIView animateWithDuration:0.25f animations:^{
        self.alpha = 0;
        
        CGRect pickerRect = self.pickerView.frame;
        pickerRect.origin.y = self.bounds.size.height;
        self.pickerView.frame = pickerRect;
        
    } completion:^(BOOL finished) {
        _show = NO;
        
        if (self.handler) {
            self.handler(self, self.finished);
        }
        
        [self removeFromSuperview];
        
    }];
    
}


- (void)cancel{
    if (!self.isShowing) {
        return;
        
    }
    
    [UIView animateWithDuration:0.25f animations:^{
        self.alpha = 0;
        CGRect pickerRect = self.pickerView.frame;
        pickerRect.origin.y = self.bounds.size.height;
        self.pickerView.frame = pickerRect;
        
    } completion:^(BOOL finished) {
        _show = NO;
        
        if (self.handler) {
            self.handler(nil, self.finished);
        }
        [self removeFromSuperview];
        
    }];
}

- (NSString *)getDateString
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    if (self.type == HYDatePickerTypeFull) {
        [formatter setDateFormat:FULL_DATE_FORMAT];
        
    } else {
        [formatter setDateFormat:PLAIN_DATE_FORMAT];
        
    }
    NSDate *date = [self getDate];
    
    return [formatter stringFromDate:date];
    
}

- (NSDate *)getDate
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd-HH-mm"];
    NSDate *date = [formatter dateFromString:[NSString stringWithFormat:@"%d-%d-%d-%d-%d", self.year, self.month, self.day, self.hour, self.minute]];
    return date;
}

#pragma mark - UIPickerViewDelegate and DataSource -

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    if (self.type == HYDatePickerTypeFull) {
        return 5;
        
    }
    return 3;
    
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    switch (component) {
        case 0:
            return YEAR_CIRCULATE_TIMES * YEAR_COUNT;
            break;
            
        case 1:
            return MONTH_CIRCULATE_TIMES * MONTH_COUNT;
            break;
            
        case 2:
            return [self calculateForDays] * DAY_CIRCULATE_TIMES;
            break;
            
        case 3:
            return HOUR_CIRCULATE_TIMES * HOUR_COUNT;
            break;
            
        case 4:
            return MINUTE_CIRCULATE_TIMES * MINUTE_COUNT;
            break;
            
        default:
            return 0;
            break;
    }
    
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
    if (self.type == HYDatePickerTypeFull) {
        return 58.f;
        
    } else {
        return 90.f;
        
    }
    
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    UILabel *label = nil;
    if (self.type == HYDatePickerTypeFull) {
        label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 58, 20)];
        label.font = [UIFont boldSystemFontOfSize:13.f];
        
    } else {
        label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 90, 20)];
        label.font = [UIFont boldSystemFontOfSize:17.f];
    }
    
    label.backgroundColor = [UIColor clearColor];
    label.textAlignment = NSTextAlignmentCenter;
    switch (component) {
        case 0:
            label.text = [NSString stringWithFormat:@"%ld年", row % YEAR_COUNT + 1900];
            break;
            
        case 1:
            label.text = [NSString stringWithFormat:@"%.2ld月", row % MONTH_COUNT + 1];
            break;
            
        case 2:
            label.text = [NSString stringWithFormat:@"%.2ld日", row % [self calculateForDays] + 1];
            break;
            
        case 3:
            label.text = [NSString stringWithFormat:@"%.2ld时", row % HOUR_COUNT];
            break;
            
        case 4:
            label.text = [NSString stringWithFormat:@"%.2ld分", row % MINUTE_COUNT];
            break;
            
        default:
            return nil;
            break;
    }
    return label;
    
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    //是否选择了时间的标识符改为YES
    if (!self.finished) {
        self.finished = YES;
        
    }
    
    switch (component) {
        case 0:
            _year = row % YEAR_COUNT + 1900;
            
            //更新day
            [pickerView reloadComponent:2];
            
            if ([self calculateForDays] < self.day) {
                _day = (int)[self calculateForDays];
                
            }
            
            [pickerView selectRow:[self calculateMiddleIndexWithFirstIndex:self.day - 1 circulateTimes:DAY_CIRCULATE_TIMES elementCount:[self calculateForDays]] inComponent:2 animated:NO];
            
            _day = (int)[pickerView selectedRowInComponent:2] % [self calculateForDays] + 1;
            
            //复原到中间位置
            [pickerView selectRow:[self calculateMiddleIndexWithFirstIndex:self.year - 1900 circulateTimes:YEAR_CIRCULATE_TIMES elementCount:YEAR_COUNT] inComponent:0 animated:NO];

            break;
        
        case 1:
            _month = row % MONTH_COUNT + 1;
            
            //更新day
            [pickerView reloadComponent:2];
            
            if ([self calculateForDays] < self.day) {
                _day = (int)[self calculateForDays];
                
            }
            
            [pickerView selectRow:[self calculateMiddleIndexWithFirstIndex:self.day - 1 circulateTimes:DAY_CIRCULATE_TIMES elementCount:[self calculateForDays]] inComponent:2 animated:NO];
            
            _day = (int)[pickerView selectedRowInComponent:2] % [self calculateForDays] + 1;
            
            //复原到中间位置
            [pickerView selectRow:[self calculateMiddleIndexWithFirstIndex:self.month - 1 circulateTimes:MONTH_CIRCULATE_TIMES elementCount:MONTH_COUNT] inComponent:1 animated:NO];

            break;
            
        case 2:
            _day = (int)row % [self calculateForDays] + 1;
            
            //复原到中间位置
            [pickerView selectRow:[self calculateMiddleIndexWithFirstIndex:self.day - 1 circulateTimes:DAY_CIRCULATE_TIMES elementCount:[self calculateForDays]] inComponent:2 animated:NO];

            break;
            
        case 3:
            _hour = row % HOUR_COUNT;
            
            [pickerView selectRow:[self calculateMiddleIndexWithFirstIndex:self.hour circulateTimes:HOUR_CIRCULATE_TIMES elementCount:HOUR_COUNT] inComponent:3 animated:NO];
            
            break;
            
        case 4:
            _minute = row % MINUTE_COUNT;
            
            [pickerView selectRow:[self calculateMiddleIndexWithFirstIndex:self.minute circulateTimes:MINUTE_CIRCULATE_TIMES elementCount:MINUTE_COUNT] inComponent:4 animated:NO];
            
            break;
            
        default:
            break;
    }
//    NSLog(@"%d年, %d月, %d日, %d时, %d分", self.year, self.month, self.day, self.hour, self.minute);
    
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end
